import 'package:flutter/material.dart';

class SwitchDetail extends StatefulWidget {

  String title;
  bool initValue;
  ValueChanged<bool> onChanged;

  SwitchDetail(this.title, {this.initValue = true, this.onChanged});

  _SwitchDetailState state;

  @override
  State<StatefulWidget> createState() {
    state = _SwitchDetailState();
    return state;
  }

  get value {
    return state.value;
  }

  set value(bool b) {
    state.value = b;
  }
}

class _SwitchDetailState extends State<SwitchDetail> {

  bool _value;

  get value {
    return _value;
  }

  set value(bool b) {
    setState(() {
      _value = b;
    });
    //只更新自身，不触发widget.onChanged
  }

  @override
  void initState() {
    super.initState();
    _value = widget.initValue;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left:18.0, right: 18.0),
      height: 48.0,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          new Expanded(child: new Text(widget.title)),
          new Container(  //嵌套一个Container使点击Switch时也会改变其状态
            child: new Switch(
              value: _value,
              onChanged: (b) {
                setState(() { //要把改变后的值更新到switch中的value中去，手动复原时才会触发
                  _value = b;
                });
                widget.onChanged(b);
              },
            ),
          ),
        ],
      ),
    );
  }
}